package climspace.ejb;

import javax.annotation.Resource;
import javax.ejb.Remote;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;

import climspace.hadoop.ArchiveStation;
import climspace.hadoop.ArchiveStationImpl;

@Stateless
@Remote(UploadStationInterface.class)
public class UploadStationBean implements UploadStationInterface {
	
	private static final long serialVersionUID = -8644844994619078937L;
	@Resource
	private SessionContext ctx;
	
	public void processFile(String fileName, String fileType) {
		sendMessage(fileName, fileType);
	}

	private void sendMessage(String fileName, String fileType) {
		QueueSession session = null;
		QueueSender sender = null;
		QueueConnection cnn = null;
		try {
			Queue queue = (Queue) ctx.lookup("queue/climspace/rdbms");

			QueueConnectionFactory factory = (QueueConnectionFactory) ctx
					.lookup("ConnectionFactory");
			cnn = factory.createQueueConnection();
			session = cnn.createQueueSession(false,
					QueueSession.AUTO_ACKNOWLEDGE);
			sender = session.createSender(queue);

			MapMessage mapMessage = session.createMapMessage();
			mapMessage.setString("fileName", fileName);
			mapMessage.setString("fileType", fileType);
			
			sender.send(mapMessage);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				sender.close();
				session.close();
				cnn.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void uploadDataByMesonet(String mesonet, String fileName) {
		// TODO ArchiveStation with default configurations
		ArchiveStation archiveStation = new ArchiveStationImpl();
		archiveStation.uploadDataFileMesonet(fileName, mesonet);		
	}
}
